package com.flyqiu.flow.core.deploy;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyqiu.common.bean.FlyQiuBeanManage;
import com.flyqiu.common.tools.StringTools;
import com.flyqiu.common.user.FlyQiuUserTools;
import com.flyqiu.flow.api.context.FlyQiuFlowGlobalContext;
import com.flyqiu.flow.api.deploy.IFlowDeploy;
import com.flyqiu.flow.api.element.FlyQiuFlowElementManage;
import com.flyqiu.flow.common.enums.ProcDeployType;
import com.flyqiu.flow.mapper.ProcDeploySourceMapper;
import com.flyqiu.flow.model.entity.ProcDeployDef;
import com.flyqiu.flow.model.entity.ProcDeploySource;

/**
 * 全自动流程发布
 */
public class FullyAutomaticProcDeploy implements IFlowDeploy {


    private final ProcDeploySourceMapper procDeploySourceMapper;

    private final FlyQiuFlowElementManage procElementManage;

    private final FlyQiuFlowGlobalContext globalContext;

    public FullyAutomaticProcDeploy(FlyQiuFlowGlobalContext globalContext) {
        this.globalContext = globalContext;
        FlyQiuBeanManage procBean = globalContext.getBeanManage();
        this.procElementManage = globalContext.getFlowElementManage();
        this.procDeploySourceMapper = procBean.getMapper(ProcDeploySourceMapper.class);
    }


    @Override
    public ProcDeploySource deploy(JSONObject modelSource, String procDefKey, String procName, String category) {
        LambdaQueryWrapper<ProcDeploySource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProcDeploySource::getDeployModelKey, procDefKey);
        queryWrapper.eq(StringTools.isNotBlank(FlyQiuUserTools.getTenantId()), ProcDeploySource::getTenantId, FlyQiuUserTools.getTenantId());
        Long count = procDeploySourceMapper.selectCount(queryWrapper);
        ProcDeploySource procDeploySource = new ProcDeploySource();
        procDeploySource.setDeployModelKey(procDefKey);
        procDeploySource.setDeploySource(modelSource);
        procDeploySource.setDeploySourceVersion((int) (count + 1));
        procDeploySource.setTenantId(FlyQiuUserTools.getTenantId());
        procDeploySourceMapper.insert(procDeploySource);
        return procDeploySource;
    }

    @Override
    public void deleteDeploy(ProcDeployDef procDeployDef) {
        procDeploySourceMapper.deleteById(procDeployDef.getDeploySourceId());
    }

    @Override
    public JSONObject getModelSource(String deploySourceId) {
        ProcDeploySource procDeploySource = procDeploySourceMapper.selectById(deploySourceId);
        return procDeploySource.getDeploySource();
    }

    /**
     * 流程部署唯一标识
     *
     * @return
     */
    @Override
    public String procDeployKey() {
        return ProcDeployType.FULLY_AUTOMATIC.getValue();
    }

    /**
     * 流程部署器名称
     *
     * @return
     */
    @Override
    public String procDeployName() {
        return ProcDeployType.FULLY_AUTOMATIC.getLabel();
    }

}
